package com.tmt.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerInHandler2 extends ChannelInboundHandlerAdapter{

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("in channelRegistered2");
		super.channelRegistered(ctx);
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("in channelUnregistered2");
		super.channelUnregistered(ctx);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("in channelActive2");
		super.channelActive(ctx);
		// 自动促发数据读取
		ctx.read();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("in channelInactive2");
		super.channelInactive(ctx);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("in channelRead2");
		if (msg != null) {
			System.out.println("收到消息 in two");
			
			//回复一个消息
			// 给服务器法送数据
			byte[] req = "Hello world".getBytes();// 消息
			ByteBuf firstMessage = Unpooled.buffer(req.length);// 发送类
			firstMessage.writeBytes(req);// 发送
			ctx.writeAndFlush(firstMessage);// flush
		}
		//super.channelRead(ctx, msg);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		System.out.println("in channelReadComplete2");
		super.channelReadComplete(ctx);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		System.out.println("in userEventTriggered2");
		super.userEventTriggered(ctx, evt);
	}

	@Override
	public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
		System.out.println("in channelWritabilityChanged2");
		super.channelWritabilityChanged(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("in exceptionCaught2");
		super.exceptionCaught(ctx, cause);
	}
}
